﻿using System;
using System.Collections.Generic;
using System.Linq;
using FingerTip.Infrastructure.NotifyMessager.Provider;

namespace FingerTip.Infrastructure.NotifyMessager
{
    public static class MessageContext
    {
        private static Dictionary<MessageType, MessageProviderType> _configs =
            new Dictionary<MessageType, MessageProviderType>();

        private static Dictionary<MessageProviderType, IProviderBase> _providerConfigs =
            new Dictionary<MessageProviderType, IProviderBase>();
        public static void Initialize()
        {
            MessageType.BugfixSolvedNotify.UseEnterpriseWechat();
            MessageType.BuildFailureNotify.UseEnterpriseWechat();
            MessageType.BuildFailureSolvedNotify.UseEnterpriseWechat();
        }


        public static void Send(this Message message)
        {
            message.IgnoreSomeboys().GetQQGroupNumbers().GetProviders().Send();
        }

        private static MessageProviderType Use(this MessageType messageType, MessageProviderType providerType)
        {
            if (_configs.Keys.Contains(messageType))
            {
                _configs[messageType] = providerType;
            }
            else
            {
                _configs.Add(messageType, providerType);
            }

            return providerType;
        }

        private static void Use<T>(this MessageProviderType providerType) where T : IProviderBase, new()
        {
            if (_providerConfigs.Keys.Contains(providerType))
            {
                _providerConfigs[providerType] = new T();
            }
            else
            {
                _providerConfigs.Add(providerType, new T());
            }
        }

        public static void UseEnterpriseWechat(this MessageType messageType)
        {
            messageType.Use(MessageProviderType.EnterpriseWeChat).Use<EnterpriseWechatGroupProvider>();
        }

        private static Message IgnoreSomeboys(this Message message)
        {
            return message;
        }

        private static Message GetQQGroupNumbers(this Message message)
        {
            return message;
        }

        private static IProviderBase GetProviders(this Message message)
        {
            if (_configs.Keys.Contains(message.MessageType))
            {
                var providerType = _configs[message.MessageType];
                if (_providerConfigs.Keys.Contains(providerType))
                {
                    var provider = _providerConfigs[providerType];
                    var t = provider.GetType();
                    if (Activator.CreateInstance(t, true) is IProviderBase result)
                    {
                        result.Setup(message);
                        return result;
                    }
                }
            }
            return null;
        }
        
    }
}